package com.qbw.app.module.vehicle.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import androidx.annotation.NonNull;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.lib.util.ResUtil;
import com.lib.util.ScreenUtil;
import com.qbw.actionmanager.ActionManager;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.action.ScanAction;
import com.qbw.app.databinding.VehicleActivityAddByScanBinding;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.common.util.FlashLightUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.app.module.scan.camera.CameraManager;
import com.qbw.app.module.scan.decoding.InactivityTimer;
import com.qbw.app.module.scan.view.ViewfinderView;
import com.qbw.core.observable.ObservableBoolean;
import com.qbw.core.observable.ObservableInt;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author QBW
 * @date 2019/10/9
 */
public class VehicleAddByScanActivity extends CommonActivity<VehicleActivityAddByScanBinding> implements SurfaceHolder.Callback {

    public static final int REQ_PERMISSION = 1;

    private Handler mUiHandler = new Handler();
    private com.qbw.app.module.scan.decoding.CaptureActivityHandler handler;
    private com.qbw.app.module.scan.view.ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private com.qbw.app.module.scan.decoding.InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private String photo_path;
    private Bitmap scanBitmap;
    //	private Button cancelScanButton;
    private String mType;
    private ObservableBoolean mLightOn = new ObservableBoolean();
    private FlashLightUtil mFlashLightUtil;

    /**
     * 扫描的状态
     */
    private ObservableInt mStatus = new ObservableInt();
    private ObservableBoolean mInvalidNet = new ObservableBoolean();


    public static void start(Context context, String type) {
        Intent intent = new Intent(context, VehicleAddByScanActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_TYPE, type);
        context.startActivity(intent);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.vehicle_activity_add_by_scan;
    }

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;
        mType = args.getString(Constant.KEY_TYPE);
        mBinding.title.setListener(this);
        CameraManager.init(getApplication());
        CameraManager.get().setAreaHeight((int) (ScreenUtil.getScreenWidth(this) * 0.43f));
        viewfinderView = mBinding.viewfinderContent;
        //		cancelScanButton = (Button) this.findViewById(R.id.btn_cancel_scan);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        mBinding.tvManual.setOnClickListener(this);
        mBinding.ivFlash.setOnClickListener(this);
        mBinding.setFlash(mLightOn);
        if (VehicleAddActivity.SCAN_TYPE_ENGINE.equals(mType)) {
            mBinding.tvManual.setText(R.string.vehicle_engine_no_manual);
        }
    }


    private void reStartScan() {
        if (handler != null) {
            handler.sendEmptyMessage(R.id.restart_preview);
        }
    }

    /**
     * 扫描二维码图片的方法
     *
     * @param path
     * @return
     */
    public Result scanningImage(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        Hashtable<DecodeHintType, String> hints = new Hashtable<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 先获取原大小
        scanBitmap = BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false; // 获取新的大小
        int sampleSize = (int) (options.outHeight / (float) 200);
        if (sampleSize <= 0) sampleSize = 1;
        options.inSampleSize = sampleSize;
        scanBitmap = BitmapFactory.decodeFile(path, options);
        com.qbw.app.module.scan.decoding.RGBLuminanceSource source = new com.qbw.app.module.scan.decoding.RGBLuminanceSource(
                scanBitmap);
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        try {
            return reader.decode(bitmap1, hints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int vid = v.getId();
        if (vid == R.id.tv_manual) {
            finish();
        } else if (vid == R.id.iv_flash) {
            mLightOn.setValue(!mLightOn.isValue());
            mFlashLightUtil.tryLightSwitch(this, mLightOn.isValue());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        startScanner();
        String[] perms = new String[]{Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            //do nothing
        } else {
            EasyPermissions.requestPermissions(this,
                                               ResUtil.getString(R.string.rotional_camera),
                                               REQ_PERMISSION,
                                               perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    private void startScanner() {
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.scanner_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        com.qbw.app.module.scan.camera.CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        /*if (mLightOn.isValue()) {
            mFlashLightUtil.tryLightSwitch(this, false);
        }*/
        mUiHandler.removeCallbacksAndMessages(null);
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    /**
     * Handler scan result
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        if (TextUtils.isEmpty(resultString)) {
            UniversalToastUtil.showToast("Scan failed!");
        } else {
            /*Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("result", resultString);
            // 不能使用Intent传递大于40kb的bitmap，可以使用一个单例对象存储这个bitmap
            //            bundle.putParcelable("bitmap", barcode);
            resultIntent.putExtras(bundle);
            this.setResult(RESULT_OK, resultIntent);*/
            //Toast.makeText(this, resultString, Toast.LENGTH_SHORT).show();
            //mUserPresenter.addCar(mCarName, 1, resultString);
            //Go.InstallObdActivity().from(this).go();
            ActionManager.getInstance().triggerAction(new ScanAction(mType, resultString));
            finish();
        }
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            com.qbw.app.module.scan.camera.CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
//            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
        mFlashLightUtil = new FlashLightUtil(CameraManager.get().getCamera());
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                                          file.getStartOffset(),
                                          file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
//            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    @Override
    public void onLeftAreaClick() {
        finish();
    }

    @Override
    public void onRightAreaClick() {

    }

    @Override
    public void onCenterAreaClick() {
        //mStatus.setValue((mStatus.getValue() + 1) % 3);//todo 测试代码
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(Constant.KEY_TYPE, mType);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

        }
    }
}
